<template>
  <a-modal v-model:open="open" width="800px" title="上传文件" @ok="handleOk">
    <a-form :model="formState" ref="formRef">
      <a-form-item
        name="keys"
        label="比对字段"
        :rules="[{ required: true, message: '请选择比对字段', type: 'array' }]"
      >
        <a-checkbox-group
          v-model:value="formState.keys"
          name="checkboxgroup"
          :options="keysOptions"
        />
      </a-form-item>

      <a-form-item
        name="valueKeys"
        label="合并字段"
        :rules="[{ required: true, message: '请选择合并字段', type: 'array' }]"
      >
        <a-checkbox-group
          v-model:value="formState.valueKeys"
          name="checkboxgroup"
          :options="valueKeysOptions"
        />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button key="back" @click="handleCancel">关闭</a-button>
      <a-button key="submit" type="primary" @click="handleMerge">合并</a-button>
      <a-button key="submit" type="primary" @click="handleExport" :disabled="!canExport">
        导出
      </a-button>
      <a-button key="submit" type="primary" @click="handleOk">确认</a-button>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
import * as XLSX from 'xlsx'
type IData = { columns: any[]; dataSource: any[]; originalData: any[] }
import { ref, computed, reactive } from 'vue'
const open = ref(false)
const formRef = ref<any>(null)
const emit = defineEmits(['ok'])
const columns = ref<any[]>([])
const dataSource = ref<IData[]>([])
let newDataSource: any[] = []
let originalData: any[] = []
const canExport = ref(false)
const formState = reactive({
  keys: [],
  valueKeys: []
})

const keysOptions = computed(() => {
  return columns.value.map((v: any) => ({
    label: v.dataIndex,
    value: v.dataIndex,
    disabled: formState.valueKeys.includes(v.dataIndex as never)
  }))
})

const valueKeysOptions = computed(() => {
  return columns.value.map((v: any) => ({
    label: v.dataIndex,
    value: v.dataIndex,
    disabled: formState.keys.includes(v.dataIndex as never)
  }))
})

const handleOk = async () => {
  await formRef.value.validate()
  open.value = false
}

const handleCancel = () => {
  open.value = false
}

const handleMerge = async () => {
  await formRef.value.validate()
  // 1 根据出入库将要计算的值改为正负
  let list = setPlusMinus(dataSource.value)
  // 2 根据比对字段生成uuid
  list = setUuid(list)
  // 3 根据uuid分组
  list = setGroup(list)
  // 4 根据分组进行计算
  list = calculateByGroup(list)
  newDataSource = list
  canExport.value = true
  localStorage.setItem('keys', JSON.stringify([...formState.keys]))
  localStorage.setItem('valueKeys', JSON.stringify([...formState.valueKeys]))
  console.log('list', list)
}

const setPlusMinus = (data: any[]) => {
  return data.map((v: any) => {
    formState.valueKeys.forEach((key: string) => {
      if (v[key] > 0) {
        v[key] = v.type === '入库' ? v[key] * 1 : v[key] * -1
      }
    })
    return v
  })
}

const setUuid = (data: any[]) => {
  return data.map((v: any) => {
    return {
      ...v,
      uuid: formState.keys.map((key) => v[key]).join('__')
    }
  })
}

const setGroup = (data: any[]) => {
  const uuidKeys = Array.from(new Set(data.map((v) => v.uuid)))
  return uuidKeys.map((key) => {
    return data.filter((v) => v.uuid === key)
  })
}

const calculateByGroup = (data: any[][]) => {
  return data.map((list: any[]) => {
    const obj: Record<string, any> = {}
    formState.valueKeys.forEach((key) => {
      obj[key] = 0
    })
    const listKeys = Object.keys(list[0])
    list.map((v: any) => {
      listKeys.forEach((key: string) => {
        if (formState.valueKeys.includes(key as never)) {
          obj[key] = v[key] * 1 + obj[key]
        } else {
          obj[key] = v[key]
        }
      })
    })

    return obj
  })
}

const handleExport = () => {
  const list = [
    {
      name: '库存表',
      dataSource: getExcelData(columns.value, newDataSource as any[])
    },
    ...(originalData as any[]).map((item) => {
      return {
        name: `${item.name}_${item.type}`,
        dataSource: getExcelData(columns.value, item.dataSource)
      }
    })
  ]

  const wb = XLSX.utils.book_new()
  console.log('xxxxxlist', list)
  list.forEach((item: any) => {
    console.log('item.dataSource', Array.isArray(item.dataSource))
    const sheet = XLSX.utils.aoa_to_sheet(item.dataSource)
    XLSX.utils.book_append_sheet(wb, sheet, item.name)
  })
  XLSX.writeFile(wb, '库存表.xlsx')
}

const getExcelData = (headers: any[], data: any[]) => {
  return [
    headers.map((v) => v.dataIndex),
    ...data.map((item) => {
      return headers.map((header) => item[header.dataIndex])
    })
  ]
}

defineExpose({
  open: (data: IData) => {
    formState.keys = JSON.parse(localStorage.getItem('keys') || '[]')
    formState.valueKeys = JSON.parse(localStorage.getItem('valueKeys') || '[]')
    open.value = true
    columns.value = data.columns
    dataSource.value = data.dataSource
    originalData = data.originalData
    console.log('columns.value', data)
  }
})
</script>
<style lang="less" scoped></style>
